package com.pospi.pospihold.ui.cash_ui;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.pospi.pospihold.App;
import com.pospi.pospihold.R;
import com.pospi.pospihold.adapter.ScanReceiptAdapter;
import com.pospi.pospihold.dao.GoodsDao;
import com.pospi.pospihold.dao.OrderDao;
import com.pospi.pospihold.dto.CashierMsgDto;
import com.pospi.pospihold.dto.GoodsDto;
import com.pospi.pospihold.dto.OrderDto;
import com.pospi.pospihold.http.MaxNO;
import com.pospi.pospihold.ui.CaptureActivity;
import com.pospi.pospihold.ui.base.BaseActivity;
import com.pospi.pospihold.ui.pay_ui.PayActivity;
import com.pospi.pospihold.util.Constant;
import com.pospi.pospihold.util.DoubleSave;
import com.pospi.pospihold.util.GetData;
import com.pospi.pospihold.util.PareseJson;
import com.pospi.pospihold.util.SaveOrderInfo;
import com.pospi.pospihold.util.TurnSize;
import com.pospi.pospihold.view.swipemenulistview.SwipeMenu;
import com.pospi.pospihold.view.swipemenulistview.SwipeMenuCreator;
import com.pospi.pospihold.view.swipemenulistview.SwipeMenuItem;
import com.pospi.pospihold.view.swipemenulistview.SwipeMenuListView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ScanReceiptActivity extends BaseActivity {

    @Bind(R.id.tv_cashier)
    TextView tvCashier;
    @Bind(R.id.sale_et)
    EditText saleEt;
    @Bind(R.id.iv_vip)
    ImageView ivVip;
    @Bind(R.id.iv_scan)
    ImageView ivScan;
    @Bind(R.id.tv_order_id)
    TextView tvOrderId;
    @Bind(R.id.lv_goods)
    SwipeMenuListView lvGoods;
    @Bind(R.id.tv_money)
    TextView tvMoney;
    @Bind(R.id.retain)
    TextView retain;
    @Bind(R.id.settle)
    TextView settle;
    @Bind(R.id.order_detail)
    ImageView orderDetail;
    @Bind(R.id.ll_bottom)
    LinearLayout llBottom;

    private GoodsDao goodsDao;
    private List<GoodsDto> goodsDtos;
    private ScanReceiptAdapter adapter;
    public final static String PUT_MONEY = "money";
    public final static String PUT_MAXNO = "maxNO";

    private EditText et_num;
    private EditText et_zr;
    private EditText et_zc;

    private int maxNO;
    private OrderDto orderDto;
    private DialogClickListener clicklistener = new DialogClickListener();
    private DialogRadioButton buttonListener = new DialogRadioButton();
    private AlertDialog diacountDialog;

    private RadioButton radioButton_zr;
    private RadioButton radioButton_zc;

    private GoodsDto selectGood;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_scan_receipt);
        ButterKnife.bind(this);
        setTitle("扫码收款");
        setMenuText("清空");

        lvGoods.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectGood = goodsDtos.get(position);
                showDialog();
            }
        });
        lvGoods.setFocusable(false);
        saleEt.requestFocus();


        LinearLayout activity_main = (LinearLayout) findViewById(R.id.activity_main);

        activity_main.setOnTouchListener(new View.OnTouchListener()

        {
            public boolean onTouch(View arg0, MotionEvent arg1) {
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

                return imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

            }

        });

        lvGoods.setOnTouchListener(new View.OnTouchListener()

        {
            public boolean onTouch(View arg0, MotionEvent arg1) {
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

                return imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

            }

        });

        initWeidgets();
    }


    public void showDialog() {
        View discountView = LayoutInflater.from(this).inflate(R.layout.goods_edit, null);
        diacountDialog = new AlertDialog.Builder(this)
                .setView(discountView)
                .create();
        Button cancle = (Button) discountView.findViewById(R.id.btn_detail_cancle);
        Button sure = (Button) discountView.findViewById(R.id.btn_detail_sure);

        et_num = (EditText) discountView.findViewById(R.id.et_num);
//        EditText price = (EditText) discountView.findViewById(R.id.et_price);
        et_zr = (EditText) discountView.findViewById(R.id.et_zr);
        et_zc = (EditText) discountView.findViewById(R.id.et_zc);

        ImageView jia = (ImageView) discountView.findViewById(R.id.iv_jia);
        ImageView jian = (ImageView) discountView.findViewById(R.id.iv_jian);

        radioButton_zr = (RadioButton) discountView.findViewById(R.id.radioButton_zr);
        radioButton_zc = (RadioButton) discountView.findViewById(R.id.radioButton_zc);
        radioButton_zr.setChecked(true);
        radioButton_zc.setChecked(false);

        cancle.setOnClickListener(clicklistener);
        sure.setOnClickListener(clicklistener);
        jia.setOnClickListener(clicklistener);
        jian.setOnClickListener(clicklistener);


        radioButton_zc.setOnCheckedChangeListener(buttonListener);
        radioButton_zr.setOnCheckedChangeListener(buttonListener);
        diacountDialog.show();
        et_num.setText(String.valueOf(selectGood.getNum()));

    }

    @Override
    protected void onStart() {
        super.onStart();
        saleEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                judgeCode(saleEt.getText().toString().trim());
            }
        });
        saleEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 先隐藏键盘
                    ((InputMethodManager) saleEt.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(
                                    ScanReceiptActivity.this.getCurrentFocus().getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);

                    if (!saleEt.getText().toString().isEmpty()) {
                        GoodsDto goodsDto = goodsDao.selectGoods(saleEt.getText().toString());
                        if (goodsDto == null) {
                            Toast.makeText(getApplicationContext(), "商品不存在", Toast.LENGTH_SHORT).show();
                        } else {
                            judgeCode(saleEt.getText().toString().trim());
                        }
                    }
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void onMenuClick(View view) {
        super.onMenuClick(view);
        //"清空"按钮的点击事件
        deleteOrder();
    }

    public void initWeidgets() {
        orderDto = (OrderDto) getIntent().getSerializableExtra(RestOrderActivity.REST_ORDER);
        if (orderDto != null) {
            maxNO = orderDto.getMaxNo();
            Log.i("跳转之后", "NO" + orderDto.getMaxNo() + "");
            goodsDtos = SaveOrderInfo.changeToList(orderDto.getOrder_info());
        } else {
            maxNO = MaxNO.getMaxNo(getApplicationContext());
            goodsDtos = new ArrayList<>();
        }
        goodsDao = new GoodsDao(getApplicationContext());

        tvOrderId.setText(String.valueOf(maxNO));
        adapter = new ScanReceiptAdapter(getApplicationContext(), goodsDtos);

        int which = getSharedPreferences("islogin", MODE_PRIVATE).getInt("which", 0);
        List<CashierMsgDto> cashierMsgDtos = new PareseJson().parese(getSharedPreferences("cashierMsgDtos", MODE_PRIVATE).getString("cashierMsgDtos", ""));
        String name = cashierMsgDtos.get(which).getName();
        tvCashier.setText(name);
        lvGoods.setAdapter(adapter);
        setSwipeListView();
        setData();
    }

    public void setData() {
        double dou = 0;
        for (int i = 0; i < goodsDtos.size(); i++) {
            dou = dou + goodsDtos.get(i).getNum() * goodsDtos.get(i).getPrice() - goodsDtos.get(i).getDiscount();
        }
        BigDecimal b = new BigDecimal(Double.parseDouble(String.valueOf(dou)));
        double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        tvMoney.setText(String.valueOf(f1));
    }

    private void setSwipeListView() {
        // step 1. create a MenuCreator
        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                // create "open" item
                SwipeMenuItem openItem = new SwipeMenuItem(
                        getApplicationContext());
                // set item background
                openItem.setBackground(new ColorDrawable(Color.rgb(0xD9, 0x47,
                        0x47)));
                // set item width
                openItem.setWidth(dp2px(90));
                // set item title
                openItem.setTitle("删除");
                // set item title fontsize
                openItem.setTitleSize(18);
                // set item title font color
                openItem.setTitleColor(Color.WHITE);
                // add to menu
                menu.addMenuItem(openItem);
            }
        };
        // set creator
        lvGoods.setMenuCreator(creator);

        // step 2. listener item click event
        lvGoods.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(int position, SwipeMenu menu, int index) {
                GoodsDto item = goodsDtos.get(position);
//					delete(item);
                goodsDtos.remove(position);
                adapter.notifyDataSetChanged();
                setData();
            }
        });

        // set SwipeListener
        lvGoods.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {

            @Override
            public void onSwipeStart(int position) {
                // swipe start
            }

            @Override
            public void onSwipeEnd(int position) {
                // swipe end
            }
        });
    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    @OnClick({R.id.retain, R.id.settle, R.id.iv_vip, R.id.iv_scan, R.id.order_detail})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_vip:
                break;
            case R.id.iv_scan:
                intent = new Intent(ScanReceiptActivity.this, CaptureActivity.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.retain:
                if (goodsDtos.isEmpty()) {
                    showToast("请添加商品");
                } else {
                    final AlertDialog deleteDialog = new AlertDialog.Builder(this)
                            .setTitle("提示")
                            .setMessage("确定挂单？")
                            .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    addRestOrderinfo();
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            })
                            .create();
                    deleteDialog.show();
                }
                break;
            case R.id.settle:
                if (goodsDtos.isEmpty()) {
                    showToast("请添加商品");
                } else {
                    SaveOrderInfo.saveAsJson(getApplicationContext(), goodsDtos);
                    intent = new Intent(ScanReceiptActivity.this, PayActivity.class);
                    intent.putExtra(PUT_MONEY, Double.parseDouble(tvMoney.getText().toString()));
                    intent.putExtra(PUT_MAXNO, maxNO);
                    startActivity(intent);
                    goodsDtos.clear();
                    adapter.notifyDataSetChanged();
                    setData();
                }
                break;
            case R.id.order_detail:
                LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
                View contentView = mLayoutInflater.inflate(R.layout.scan_recepit_detail, null);
                // R.layout.pop为PopupWindow 的布局文件
                PopupWindow pop = new PopupWindow(contentView, ActionBar.LayoutParams.FILL_PARENT, TurnSize.dip2px(getApplicationContext(), 150));
                pop.setBackgroundDrawable(new BitmapDrawable());
                // 指定 PopupWindow 的背景
                pop.setFocusable(true);
                //指定PopupWindow显示在你指定的view下

                int[] location = new int[2];
                llBottom.getLocationOnScreen(location);
                pop.showAtLocation(llBottom, Gravity.NO_GRAVITY, location[0], location[1] - pop.getHeight());

                TextView ys = (TextView) contentView.findViewById(R.id.detail_ys);
                TextView dMoney = (TextView) contentView.findViewById(R.id.detail_discount_money);
                TextView dNum = (TextView) contentView.findViewById(R.id.detail_discount_num);
                TextView nMoney = (TextView) contentView.findViewById(R.id.detail_normal_money);
                TextView nNum = (TextView) contentView.findViewById(R.id.detail_normal_num);
                TextView num = (TextView) contentView.findViewById(R.id.detail_num);

                double Nmoney = 0;
                int Nnum = 0;

                double discountMoney = 0;
                int discountNum = 0;
                int totalNum = 0;
                for (int i = 0; i < goodsDtos.size(); i++) {
                    totalNum += goodsDtos.get(i).getNum();
                    if (goodsDtos.get(i).getDiscount() > 0) {
                        discountNum += goodsDtos.get(i).getNum();
                        discountMoney += goodsDtos.get(i).getDiscount();
                    } else {
                        Nnum += goodsDtos.get(i).getNum();
                        Nmoney += goodsDtos.get(i).getNum() * goodsDtos.get(i).getPrice();
                    }
                }

                ys.setText(tvMoney.getText().toString());
                nMoney.setText(String.valueOf(Nmoney));
                nNum.setText(String.valueOf(Nnum));
                dMoney.setText(String.valueOf(discountMoney));
                dNum.setText(String.valueOf(discountNum));
                num.setText(String.valueOf(totalNum));
                break;
        }
    }


    /**
     * 获取扫码返回的信息
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 2) {
            if (requestCode == 1) {
                saleEt.setText(data.getStringExtra("code"));
//                judgeCode(data.getStringExtra("code"));
            }
        }
    }

    /**
     * 判断数据库里面是否有该条形码的商品
     *
     * @param code 商品的条形码
     */
    public void judgeCode(String code) {
        Log.i("code", code);
        GoodsDto goodsDto = goodsDao.selectGoods(code);
        if (goodsDto != null) {//当返回的查询数据不为空的时候
            Log.i("code_name", goodsDto.getName());
            goodsDto.setNum(1);//把商品数量设置为1
            goodsDto.setDiscount(0);
            goodsDtos.add(goodsDto);
            setData();
            adapter.notifyDataSetChanged();
            saleEt.setText("");
        }
    }

    /**
     * 删除当前的订单的信息
     */
    public void deleteOrder() {
        if (goodsDtos.isEmpty()) {
            showToast("商品为空");
        } else {
            final AlertDialog deleteDialog = new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("确定销毁该订单？")
                    .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            goodsDtos.clear();
                            adapter.notifyDataSetChanged();
                            tvMoney.setText("0.0");
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    })
                    .create();
            deleteDialog.show();
        }

    }

    public void addRestOrderinfo() {
        String shopId = getSharedPreferences("StoreMessage", MODE_PRIVATE).getString("Id", "");
        OrderDto orderDto = new OrderDto();
        orderDto.setOrder_info(SaveOrderInfo.changeGoodDtoToJson(goodsDtos));//存储的该订单的商品的信息
        orderDto.setPayway(null);
        orderDto.setTime(GetData.getYYMMDDTime());
        orderDto.setSs_money(0.00);
        orderDto.setYs_money(DoubleSave.doubleSaveTwo(Double.parseDouble(tvMoney.getText().toString())));
        orderDto.setZl_money(0.00);
        orderDto.setCashiername(App.getCashierMsgDto().getName());
        orderDto.setCashiernumber(App.getCashierMsgDto().getNumber());
        orderDto.setShop_id(shopId);
        orderDto.setOrderType(Constant.ORDERTYPE_GD);
        orderDto.setMaxNo(maxNO);
        orderDto.setCheckoutTime(GetData.getDataTime());
        orderDto.setDetailTime(GetData.getHHmmssTimet());
        orderDto.setHasReturnGoods(Constant.hasReturnGoods_No);
        orderDto.setOut_trade_no(null);
        //当挂单的时候该数据用于保存是哪个界面进行的挂单操作
        orderDto.setPayReturn(RestOrderActivity.REST_SCAN);
        orderDto.setIfFinishOrder(Constant.NO);
        /**
         * 给数据库里面添加一条记录
         */
        new OrderDao(getApplicationContext()).addOrder(orderDto);
        goodsDtos.clear();
        adapter.notifyDataSetChanged();
        tvMoney.setText("0");
        showToast("挂单成功");
    }

    class DialogClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_detail_cancle:
                    diacountDialog.dismiss();
                    break;
                case R.id.btn_detail_sure:
                    if (0 == Integer.parseInt(et_num.getText().toString())) {
                        goodsDtos.remove(selectGood);
                        adapter.notifyDataSetChanged();
                        diacountDialog.dismiss();
                    } else {
                        selectGood.setNum(Integer.parseInt(et_num.getText().toString()));
                        if (radioButton_zc.isChecked()) {
                            discount(radioButton_zc, et_zc);
                        } else if (radioButton_zr.isChecked()) {
                            discount(radioButton_zr, et_zr);
                        }
                        adapter.notifyDataSetChanged();
                        setData();
                        diacountDialog.dismiss();

                    }
                    break;
                case R.id.iv_jia:
                    try {
                        int num = Integer.parseInt(et_num.getText().toString());
                        num += 1;
                        et_num.setText(String.valueOf(num));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case R.id.iv_jian:
                    try {
                        int num = Integer.parseInt(et_num.getText().toString());
                        if (num == 0) {
                            showToast("商品数量不可小于0!");
                        } else {
                            num -= 1;
                            et_num.setText(String.valueOf(num));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }

    public void discount(RadioButton button, EditText et) {
        if (!et.getText().toString().trim().isEmpty()) {
            double value = Double.parseDouble(et.getText().toString().trim());
            if (value > 0) {
                if (button.getId() == R.id.radioButton_zc) {
                    if (value > 100) {
                        showToast("折让金额不能大于商品金额");
                    } else {
                        double discount = selectGood.getPrice() * selectGood.getNum() * (value / 100);
                        selectGood.setDiscount(DoubleSave.doubleSaveTwo(discount));
                    }
                } else if (button.getId() == R.id.radioButton_zr) {
                    if (value > selectGood.getPrice() * selectGood.getNum()) {
                        showToast("折让金额不能大于商品金额");
                    } else {
                        selectGood.setDiscount(value);
                    }
                }
            }

        }

    }

    class DialogRadioButton implements CompoundButton.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            switch (buttonView.getId()) {
                case R.id.radioButton_zc:
                    if (isChecked) {
                        radioButton_zc.setChecked(true);
                        radioButton_zr.setChecked(false);
                        et_zr.setText(null);
                    }
                    break;
                case R.id.radioButton_zr:
                    if (isChecked) {
                        radioButton_zc.setChecked(false);
                        radioButton_zr.setChecked(true);
                        et_zc.setText(null);
                    }
                    break;
            }
        }
    }
}

